import axios from 'axios';
import { Message, Loading } from 'element-ui';

const httpService = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_URL,
  // 请求超时时间
  timeout: 30000
});

/**
 * request拦截器
 */
httpService.interceptors.request.use(
	config => {

		let isNoAuth = config.headers.Authorization;

		let accessToken = sessionStorage.getItem("access_token")

		if (accessToken && !isNoAuth) {
			config.headers.Authorization = '' + accessToken;
		} else {
			config.headers.Authorization = '';
		}

		if(!config.headers['Content-Type']){
			if (config.data instanceof Object) {
				config.headers['Content-Type'] = 'application/json; charset=utf-8';
			} else {
				config.headers['Content-Type'] = 'text/plain; charset=utf-8';
			}
		}
		
		if(!config.responseType) {
			config.responseType = 'json'
		}

		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

/**
 * respone拦截器
 */
httpService.interceptors.response.use(
	response => {
		const responseType = response.config.responseType;
		const data = response.data;
		if(responseType && responseType != 'json') {
			return data;
		} else {
			if(data.success) {
				return data;
			} else {
				Message.error(data.message);
				// 返回异常
				return Promise.reject({
					response: {
						status: 500,
						statusText: data.message
					}
				});
			}
		}
	},
	error => {
		
		if (error && error.response) {
			Message.closeAll();
			const response = error.response;
			if (response.status === 401) {
				sessionStorage.removeItem('access_token');
				window.location.href = '/login'
			} else if (response.data && response.data.message) {
				Message.error(response.data.message);
			} else {
				Message.error('系统异常');
			}
		}

		return Promise.reject(error)
	}
)

const loadOption = {
	lock: true,
	text: 'Loading',
	spinner: 'el-icon-loading',
	background: 'rgba(0, 0, 0, 0.7)'
}

/**
 *  get请求
 *  url:请求地址
 *  params:参数
 */
export function get(url, params = {}) {
	const loading = Loading.service(loadOption);
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
			loading.close();
        }).catch(error => {
            reject(error);
			loading.close();
        });
    });
}

/**
 * post请求
 * url:请求地址
 * params:参数
 */
export function post(url, params = {}) {
	const loading = Loading.service(loadOption);
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params
        }).then(response => {
            resolve(response);
			loading.close();
        }).catch(error => {
            reject(error);
			loading.close();
        });
    });
}

/**
 *  文件上传
 *  url:请求地址
 *  params:参数
 */
export function fileUpload(url, params = {}) {
	const loading = Loading.service(loadOption);
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
            resolve(response);
			loading.close();
        }).catch(error => {
            reject(error);
			loading.close();
        });
    });
}

/**
 *  文件下载
 *  url:请求地址
 *  params:参数
 */
export function download(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
			data: params,
			responseType: 'blob'
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export default {
    get,
    post,
    fileUpload,
	download
}